<template>
  <el-container>
    <el-header>
      <div class="itemList-head">
        <div class="itemList-head-type">
          <span v-show="false" class="icon iconfont active icon-yingyongshezhi"></span>
          <span v-show="false" class="icon iconfont icon-daohangliebiao"></span>
        </div>
        <div v-show="false" class="itemList-head-heng"></div>
        <!--        <el-select size="mini" style="width:120px;" v-model="option.orderBy" placeholder="请选择" >-->
        <!--          <el-option key="文件名升序" label="文件名升序" value="1"></el-option>-->
        <!--          <el-option key="文件名降序" label="文件名降序" value="2"></el-option>-->
        <!--          <el-option key="上传时间升序" label="上传时间升序" value="3"></el-option>-->
        <!--          <el-option key="上传时间降序" label="上传时间降序" value="4"></el-option>-->
        <!--        </el-select>-->
        <div class="itemList-head-rank">
          <span class="iconfont icon-paixu"></span>
          <div class="rank-box">
            <ul>
              <li class="rank-list "
                  @click="pxChange('1')">
                <div class="rank-icon ">
                  <i class="next-icon pitch-on el-icon-check"></i>
                </div>
                <div>
                  <span>文件名升序</span>
                </div>
              </li>
              <li class="rank-list"
                  @click="pxChange('2')">
                <div class="rank-icon">
                  <i class="next-icon pitch-on el-icon-check"></i>
                </div>
                <div>
                  <span>文件名降序</span>
                </div>
              </li>
              <li class="rank-list"
                  @click="pxChange('3')">
                <div class="rank-icon">
                  <i class="next-icon pitch-on el-icon-check"></i>
                </div>
                <div>
                  <span>上传时间升序</span>
                </div>
              </li>
              <li class="rank-list active"
                  @click="pxChange('4')">
                <div class="rank-icon">
                  <i class="next-icon pitch-on el-icon-check"></i>
                </div>
                <div>
                  <span>上传时间降序</span>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <el-input size="mini"
                  style="width:200px;margin: 0 10px;"
                  v-model="option.sval"
                  placeholder="文件名"
                  class="input-with-select">
          <el-button slot="append"
                     icon="el-icon-search"
                     @click="search"></el-button>
        </el-input>
        <el-button size="mini"
                   @click="$refs.uploadFile.open()">上传文件</el-button>
        <div class="pic-storage"
             v-if="showUsed">
          <div>
<!--            <p class="storage-content">已用&nbsp;{{getUseStr}} <a-->
<!--                 href="javascript:void(0);"-->
<!--                 title="升级空间"><i class="icon iconfont"-->
<!--                   style="color:#3089DC;">&#xe636;</i></a></p>-->
            <p class="storage-content">已用&nbsp;{{getUseStr}} <a
                    href="javascript:void(0);"><i class="icon iconfont"
                                    style="color:#3089DC;">&#xe636;</i></a></p>
            <p class="storage-bar">
              <span class="storage-bar-used"
                    :style="{width: getUseBL}"></span>
            </p>
          </div>
        </div>
      </div>
      <uploadFile ref="uploadFile" :resType="resType"
                  @callback="uploadFileCallBack"
                  :albumId="option.albumId"></uploadFile>
    </el-header>
    <el-main>
      <div class="material-list infinite-list-wrapper" :style="{height:height}">
        <ul class="material-content clearfix"
            v-infinite-scroll="loadData"
            infinite-scroll-disabled="disabled">
          <li v-for="(item,index) in listData"
              :key="index"
              :class="{active:item.showActive}"
              @click="selItem(item,index)">
            <i v-if="item.showActive">{{item.sort}}</i>
            <div class="material-img hover"  v-if="resType == 'pic'">
              <div class="img-box">
                <img :src="item.path"
                     width="106"
                     height="106">
              </div>
              <div class="lis-img-bottom">
                <div class="sort">
                  <a @click.prevent="handlePictureCardPreview(item.path)"
                     title="图片预览"
                     class="img-bottom-icon check-iconfont icon-filepicture"></a><span>|</span>
                </div>
                <div class="sort">
                  <a @click.prevent="copyStr(item.path)"
                     title="复制链接"
                     class="img-bottom-icon check-iconfont icon-daima"></a><span>|</span>
                </div>
                <div class="sort">
                  <a @click.prevent="removeAccessory(item.id)"
                     title="删除"
                     class="img-bottom-icon check-iconfont icon-shanchu"></a>
                </div>
                <div style="clear:both;"></div>
              </div>
              <div class="lis-img-bottom single">
                <div class="sort-size">{{item.width}}*{{item.height}}</div>
              </div>
            </div>
            <div class="material-img hover"  v-if="resType == 'video'">
              <div class="img-box"><img src="../../../../public/img/mp4.png" width="106" height="106"></div>
              <div class="lis-img-bottom">
                <div class="sort">
                  <a @click.prevent.stop="play(item.path)"
                     title="播放视频"
                     class="img-bottom-icon check-iconfont icon-filepicture"></a><span>|</span>
                </div>
                <div class="sort">
                  <a @click.prevent.stop="copyStr(item.path)"
                     title="复制链接"
                     class="img-bottom-icon check-iconfont icon-daima"></a><span>|</span>
                </div>
                <div class="sort">
                  <a @click.prevent.stop="removeAccessory(item.id)"
                     title="删除"
                     class="img-bottom-icon check-iconfont icon-shanchu"></a>
                </div>
                <div style="clear:both;"></div>
              </div>
              <div class="lis-img-bottom single">
                <div class="sort-size">{{item.ext}}</div>
              </div>
            </div>

            <div class="material-name"
                 title="item.name">
              <div class="not-material name">{{item.name}}</div>
            </div>
          </li>
        </ul>
        <p v-if="option.loading"
           style="text-align: center;font-size: 13px;color:#999;">加载中...</p>
        <p v-if="option.noMore"
           style="text-align: center;font-size: 13px;color:#999;">没有更多了</p>
      </div>
      <el-dialog :visible.sync="dialogVisible"
                 width="80%"
                 height="80%"
                 append-to-body>
        <img width="100%"
             :src="dialogImageUrl"
             alt="">
      </el-dialog>
      <el-dialog :visible.sync="videodialog"
                 top="10vh"
                 width="80%"
                 height="80%"
                 destroy-on-close
                 append-to-body>
        <mvdiv :src="mvurl" ref="videoplay"></mvdiv>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import { listAccessory, removeAccessory } from "@/api/base/res/album";
import { convertFileSize } from "@/util/util";
import uploadFile from './uploadFile';
import constants from "@/const/constants";
import { OSS_URL} from "@/config/env";

import mvdiv from '@/components/videoPlayer';
export default {
  props: {
    imgNum:{
      type: String,
      default: '5'
    },
    selMaxWidth: {//可选文件最大宽度，0为不限制
      type: String,
      default: "0"
    },
    selMaxHeight: {//可选文件最大高度，0为不限制
      type: String,
      default: "0"
    },
    selectType: {//文件选择方式：radio,checkbox 单选或多选
      type: String,
      default: "radio"
    },
    height: {//文件选择方式：radio,checkbox 单选或多选
      type: String,
      default: "400px"
    },
    resType:{   //文件上传文件类型
      type:String,
      default:constants.FILE_TYPE_PIC
    },
  },
  data () {
    return {
      videodialog:false,//视频播放组件
      mvurl:'',
      arr: [],
      listData: [],//文件列表
      sellistData: [],
      showUsed: false,//显示空间使用情况
      totalSize: 1,//空间总量 单位：b
      useSize: 1,//空间使用量 单位：b
      option: {
        albumId: '0',//相册id
        orderBy: 4,//排序方式
        sval: "",//关键词
        page: 1,//当前页数
        size: 30,//每页记录数
        loading: true,//是否显示"加载中..."文字
        noMore: false//是否有更多数据
      },
      dialogImageUrl: '',//图片预览url
      dialogVisible: false,//图片预览框是否显示
    }
  },
  created(){
    this.sellistData = [];
  },
  watch:{
    'listData'(val,newval){
      if(newval.length > val.length ){
        this.sellistData = [];
      }
    }
  },
  computed: {
    getUseBL () { //容量使用比例 例如 86.22%
      return this.useSize / this.totalSize * 100 + "%";
    },
    getUseStr () {  //容量使用情况字符串 例如：500MB / 12GB
      return convertFileSize(this.useSize) + "/" + convertFileSize(this.totalSize);
    },
    disabled () { //瀑布流分页加载开关
      return this.option.loading || this.option.noMore
    },
    getActiveStat (path) {  //获取该图片是否选中
      return this.arrayFn.constansStr(this.sellistData, path);
    }
  },
  components: {
    uploadFile,
    mvdiv
  },
  methods: {
    reLoadData (albumId) {
      //重新加载数据
      //重置一些基础属性后，重新刷新文件列表
      this.option.albumId = albumId;
      this.option.page = 1;
      this.option.loading = false;
      this.option.noMore = false;
      this.listData = [];
      //加载列表数据
      this.loadData();
    },
    pxChange (orderBy) {
      //排序字段变化事件
      this.option.orderBy = orderBy;
      this.reLoadData(this.option.albumId);
    },
    search () {
      //查询方法
      this.reLoadData(this.option.albumId);
    },
    loadData () {
      //加载数据
      if (this.option.albumId == "0" ){
          //如果albumId为0，则不加载数据。
          return;
      }
      this.option.loading = true;
      //加载列表数据
      listAccessory(this.option).then(res => {
        if (res.data.code == 200) {
          this.listData = this.listData.concat(res.data.data.map((item) => {
            item.path = OSS_URL + item.path;
            return item;
          }));
          if (res.data.message != "0") {
            this.showUsed = true;
            var obj = JSON.parse(res.data.message);
            this.useSize = obj.useSize;
            this.totalSize = obj.totalSize;
          }
          setTimeout(() => {
            if (res.data.data.length < this.option.size) {
              //返回的列表长度不够一页则认为是到底部了。
              this.option.noMore = true;
            } else {
              this.option.page = this.option.page + 1;
            }
            //延时下一次加载。
            this.option.loading = false;
          }, 1000)
        } else {
          this.option.noMore = true;
          this.$message.error(res.data.message);
        }
      });
    },
    uploadFileCallBack () {
      //图片上传组件上传后回调方法
      this.reLoadData(this.option.albumId);
    },
    removeAccessory (id) {
      //删除文件事件
      this.$confirm("删除图片后，所有引用该图的地方将无法显示，确定删除吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        removeAccessory(id).then(res => {
          if (res.data.code == 200) {
            this.$message.success("删除成功！");
            //移除被删除的文件
            this.listData = this.listData.filter((item) => {
              if (item.id != id) {
                return item;
              }
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
      })

    },
    handlePictureCardPreview (url) {
      //图片预览事件
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    play(url){
      // alert(url)
      this.videodialog = true;
      setTimeout(()=>{
        this.mvurl = url
      },100)

    },
    copyStr: function (str) {
      //复制字符串到剪切板
      var input = document.createElement("input");     // 直接构建input
      input.value = str;   // 设置内容
      document.body.appendChild(input);        // 添加临时实例
      input.select();      // 选择实例内容
      document.execCommand("Copy");     // 执行复制
      document.body.removeChild(input);  // 删除临时实例

      this.$message.success("复制成功！");
    },
    selItem: function (item) {
      //选择文件事件
      if (this.selectType == "radio") {
        //单选
        this.sellistData = [];
        if (item.showActive) {
          //取消所有文件选中状态
          this.listData = this.listData.filter((o) => {
            o.showActive = false;
            return o;
          })
          item.showActive = false;
        } else {
          //取消所有文件选中状态
          this.listData = this.listData.filter((o) => {
            o.showActive = false;
            return o;
          })
          item.showActive = true;
          this.sellistData.push(item.path);
          item.sort = this.sellistData.length
        }
      } else {
        //多选
        if (item.showActive) {
          item.showActive = false;
          this.sellistData = this.arrayFn.removeStr(this.sellistData, item.path);
          //所有已选中的图片的序号减一
          for(let it of this.listData){
              if(it.showActive == true){
                  if(it.sort > item.sort){
                      it.sort=it.sort-1;
                  }
              }
          }
        } else {
         if(this.sellistData.length  <= this.imgNum-1){
           item.showActive = true;
           this.sellistData.push(item.path);
           item.sort = this.sellistData.length
         }else{
           this.$message({
             type:'warning',
             message:`最多可选择${this.imgNum}张图片`
           })
         }
        }
      }
      this.listData = this.arrayFn.updateObjByKey(this.listData, item, "id");

      //传递选中的链接到父组件中
      this.$emit('callback', this.sellistData);
    }
  }
}
</script>

<style scoped>
@import "../../../../public/css/material-center.css";
</style>